﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Formality.FormalSystem.Parser
{
    public class PrecedenceRules
    {
        public PrecedenceRules()
        {
            OperatorMap = new Dictionary<string, Operator>();
        }

        public void Add(string CanonicalSymbol, params object[] VariantSymbols)
        {
            var Precedence = ++HighestPrecedence;

            var Op = new Operator(CanonicalSymbol, Precedence);

            OperatorMap[CanonicalSymbol.ToString()] = Op;

            foreach (var Var in VariantSymbols)
                OperatorMap[Var.ToString()] = Op;
        }

        public Proposition Parse(IEnumerable<Proposition> Operands, IEnumerable<string> Operators)
        {
            var NumOperands = Operands.Count();

            if (NumOperands < 2)
                throw new Exception("Require at least two operands");

            var ExpectedOperators = NumOperands - 1;
            if (Operators.Count() != ExpectedOperators)
                throw new Exception("Expected exactly " + ExpectedOperators + " operators");

            return new PrecedenceParser<Proposition>
            {
                Operands = Operands,
                OperatorMap = OperatorMap,
                Operators = Operators,
                OperandPrecedence = HighestPrecedence + 1
            }.Parse((op, ops) => Construction.Operator(op, ops));
        }

        internal Operator this[string Key]
        {
            get { return OperatorMap[Key]; }
        }

        internal Operator TryGetOperator(string Key)
        {
            Operator Op = null;

            return OperatorMap.TryGetValue(Key, out Op) ? Op : null;
        }

        internal IEnumerable<KeyValuePair<string, Operator>> Rules
        {
            get { return OperatorMap; }
        }

        private int HighestPrecedence;

        private Dictionary<string, Operator> OperatorMap;
    }
}
